package cn.zmall.manager.service.impl;

import cn.zmall.common.exception.ZmallException;
import cn.zmall.common.jedis.JedisClient;
import cn.zmall.common.pojo.DataTablesResult;
import cn.zmall.common.utils.IDUtil;
import cn.zmall.manager.dto.DtoUtil;
import cn.zmall.manager.dto.ItemDto;
import cn.zmall.manager.mapper.TbItemCatMapper;
import cn.zmall.manager.mapper.TbItemDescMapper;
import cn.zmall.manager.mapper.TbItemMapper;
import cn.zmall.manager.pojo.TbItem;
import cn.zmall.manager.pojo.TbItemCat;
import cn.zmall.manager.pojo.TbItemDesc;
import cn.zmall.manager.pojo.TbItemExample;
import cn.zmall.manager.service.ItemService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.*;
import java.util.Date;
import java.util.List;

/**
 * @Author BinBini
 * @Date 2020/11/3 9:28
 * @Version 1.0
 */
@Service
public class ItemServiceImpl implements ItemService {

    private final static Logger log = LoggerFactory.getLogger(ItemService.class);

    @Autowired
    private TbItemMapper tbItemMapper;
    @Autowired
    private TbItemDescMapper tbItemDescMapper;
    @Autowired
    private TbItemCatMapper tbItemCatMapper;
    @Autowired
    private JmsTemplate jmsTemplate;
    @Resource
    private Destination topicDestination;
    @Autowired
    private JedisClient jedisClient;

    @Value("ITEM_INFO")
    private String PRODUCT_ITEM;

    @Override
    public ItemDto getItemById(Long id) {
        ItemDto itemDto = new ItemDto();

        TbItem tbItem = tbItemMapper.selectByPrimaryKey(id);
        itemDto = DtoUtil.TbItemToItemDto(tbItem);

        TbItemCat tbItemCat = tbItemCatMapper.selectByPrimaryKey(itemDto.getCid());
        itemDto.setCname(tbItemCat.getName());

        TbItemDesc tbItemDesc = tbItemDescMapper.selectByPrimaryKey(id);
        itemDto.setDetail(tbItemDesc.getItemDesc());

        return itemDto;
    }

    @Override
    public TbItem getNormalItemById(Long id) {
        return tbItemMapper.selectByPrimaryKey(id);
    }

    @Override
    public DataTablesResult getItemList(int draw, int start, int length, int cid, String search, String orderCol, String orderDir) {
        DataTablesResult result = new DataTablesResult();

        PageHelper.startPage(start/length + 1, length);
        List<TbItem> list = tbItemMapper.selectItemByCondition(cid, "%"+search+"%", orderCol, orderDir);
        PageInfo<TbItem> pageInfo = new PageInfo<>(list);
        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setRecordsTotal(getAllItemCount().getRecordsTotal());

        result.setDraw(draw);
        result.setData(list);
        return result;
    }

    @Override
    public DataTablesResult getItemSearchList(int draw, int start, int length, int cid, String search, String minDate, String maxDate, String orderCol, String orderDir) {
        DataTablesResult result = new DataTablesResult();

        PageHelper.startPage(start/length + 1, length);
        List<TbItem> list = tbItemMapper.selectItemByMultiCondition(cid, "%"+search+"%", minDate, maxDate, orderCol, orderDir);
        PageInfo<TbItem> pageInfo = new PageInfo<>(list);
        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setRecordsTotal(getAllItemCount().getRecordsTotal());

        result.setDraw(draw);
        result.setData(list);
        return result;
    }

    @Override
    public DataTablesResult getAllItemCount() {
        TbItemExample example = new TbItemExample();
        Long count = tbItemMapper.countByExample(example);
        DataTablesResult result = new DataTablesResult();
        result.setRecordsTotal(Math.toIntExact(count));
        return result;
    }

    @Override
    public TbItem addItem(ItemDto itemDto) {
        long id = IDUtil.getRandomId();
        TbItem tbItem = DtoUtil.ItemDtoToTbItem(itemDto);
        tbItem.setId(id);
        tbItem.setStatus((byte) 1);
        tbItem.setCreated(new Date());
        tbItem.setUpdated(new Date());
        if(tbItem.getImage().isEmpty()) {
            // 为空时的图片
            tbItem.setImage("");
        }
        if(tbItemMapper.insert(tbItem) != 1) {
            throw new ZmallException("添加商品失败");
        }

        TbItemDesc tbItemDesc = new TbItemDesc();
        tbItemDesc.setItemId(id);
        tbItemDesc.setItemDesc(itemDto.getDetail());
        tbItemDesc.setCreated(new Date());
        tbItemDesc.setUpdated(new Date());
        if(tbItemDescMapper.insert(tbItemDesc) != 1) {
            throw new ZmallException("添加商品详情失败");
        }
        // 发送消息同步索引库
        try {
            sendRefreshESMessage("add", id);
        } catch (Exception e) {
          log.error("同步索引错误");
        }
        return getNormalItemById(id);
    }

    @Override
    public TbItem updateItem(Long id, ItemDto itemDto) {
        TbItem oldTbItem = getNormalItemById(id);

        TbItem tbItem = DtoUtil.ItemDtoToTbItem(itemDto);

        if(tbItem.getImage().isEmpty()) {
            tbItem.setImage(oldTbItem.getImage());
        }
        tbItem.setId(id);
        tbItem.setStatus(oldTbItem.getStatus());
        tbItem.setCreated(oldTbItem.getCreated());
        tbItem.setUpdated(new Date());
        if(tbItemMapper.updateByPrimaryKey(tbItem) != 1) {
            throw new ZmallException("更新商品失败");
        }

        TbItemDesc tbItemDesc = new TbItemDesc();
        tbItemDesc.setItemId(id);
        tbItemDesc.setItemDesc(itemDto.getDetail());
        tbItemDesc.setCreated(oldTbItem.getCreated());
        tbItemDesc.setUpdated(new Date());

        if(tbItemDescMapper.updateByPrimaryKey(tbItemDesc) != 1) {
            throw new ZmallException("更新商品详情失败");
        }
        // 同步缓存
        deleteProductDetRedis(id);
        // 发送消息同步索引库
        try {
            sendRefreshESMessage("add", id);
        } catch (Exception e) {
            log.error("同步索引库失败");
        }
        return getNormalItemById(id);
    }

    @Override
    public TbItem alertItemState(Long id, Integer state) {
        TbItem tbItem = getNormalItemById(id);
        tbItem.setStatus(state.byteValue());
        tbItem.setUpdated(new Date());

        if(tbItemMapper.updateByPrimaryKey(tbItem) != 1) {
            throw new ZmallException("修改商品状态失败");
        }
        return getNormalItemById(id);
    }

    @Override
    public int deleteItem(Long id) {
        if(tbItemMapper.deleteByPrimaryKey(id) != 1) {
            throw new ZmallException("删除商品失败");
        }
        if(tbItemDescMapper.deleteByPrimaryKey(id) != 1) {
            throw new ZmallException("删除商品详情失败");
        }
        // 发送消息同步索引库
        try {
            sendRefreshESMessage("delete", id);
        } catch (Exception e) {
            log.error("同步索引库失败");
        }
        return 1;
    }

    /**
     * 同步商品详情缓存
     * @param id
     */
    public void deleteProductDetRedis(Long id) {
        try {
            jedisClient.del(PRODUCT_ITEM + ":" + id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送消息同步索引库
     * @param type
     * @param id
     */
    public void sendRefreshESMessage(String type, Long id) {
        jmsTemplate.send(topicDestination, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                TextMessage textMessage = session.createTextMessage(type + "," + String.valueOf(id));
                return textMessage;
            }
        });
    }
}
